package meiyunting.shiwuzhaoling.config;

import meiyunting.shiwuzhaoling.model.ItemStatus;
import meiyunting.shiwuzhaoling.model.ItemType;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.format.datetime.DateFormatterRegistrar;
import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;
import java.time.format.DateTimeFormatter;

/**
 * Web配置类，处理日期时间格式化
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Value("${file.upload-dir}")
    private String uploadDir;

    /**
     * 配置静态资源处理
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 添加静态资源处理
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/");
        
        try {
            // 获取上传目录的绝对路径
            File uploadDirectory = new File(uploadDir);
            if (!uploadDirectory.isAbsolute()) {
                uploadDirectory = new File(System.getProperty("user.dir"), uploadDir);
            }
            
            String absolutePath = uploadDirectory.getAbsolutePath().replace('\\', '/');
            if (!absolutePath.endsWith("/")) {
                absolutePath += "/";
            }
            
            String fileUrl = "file:///" + absolutePath;
            
            System.out.println("【WebConfig】配置上传目录资源映射: /uploads/images/** -> " + fileUrl);
            
            // 配置上传文件夹的资源映射
            registry.addResourceHandler("/uploads/images/**")
                    .addResourceLocations(fileUrl);
            
        } catch (Exception e) {
            System.err.println("【错误】添加资源处理器失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 配置日期时间格式化器和类型转换器
     */
    @Override
    public void addFormatters(FormatterRegistry registry) {
        // 注册标准时间格式化器
        DateTimeFormatterRegistrar dateTimeRegistrar = new DateTimeFormatterRegistrar();
        dateTimeRegistrar.setDateFormatter(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        dateTimeRegistrar.setDateTimeFormatter(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        dateTimeRegistrar.registerFormatters(registry);

        // 注册日期格式化器
        DateFormatterRegistrar dateRegistrar = new DateFormatterRegistrar();
        dateRegistrar.setFormatter(new DateFormatter("yyyy-MM-dd"));
        dateRegistrar.registerFormatters(registry);
        
        // 添加字符串到枚举的转换器
        registry.addConverter(new StringToItemTypeConverter());
        registry.addConverter(new StringToItemStatusConverter());
    }
    
    /**
     * 字符串到ItemType枚举的转换器
     */
    private static class StringToItemTypeConverter implements Converter<String, ItemType> {
        @Override
        public ItemType convert(String source) {
            try {
                System.out.println("【转换器】尝试将字符串转换为ItemType: " + source);
                return ItemType.valueOf(source);
            } catch (Exception e) {
                System.err.println("【错误】ItemType转换失败: " + e.getMessage());
                e.printStackTrace();
                return null;
            }
        }
    }
    
    /**
     * 字符串到ItemStatus枚举的转换器
     */
    private static class StringToItemStatusConverter implements Converter<String, ItemStatus> {
        @Override
        public ItemStatus convert(String source) {
            try {
                System.out.println("【转换器】尝试将字符串转换为ItemStatus: " + source);
                return ItemStatus.valueOf(source);
            } catch (Exception e) {
                System.err.println("【错误】ItemStatus转换失败: " + e.getMessage());
                e.printStackTrace();
                return null;
            }
        }
    }
} 